//
//  IOTCAddToGoogleCalendarsViewController.m
//  Tasks-Test3
//
//  Created by User-16 on 3/19/14.
//  Copyright (c) 2014 IOTrainingCamp. All rights reserved.
//

#import "IOTCAddToGoogleCalendarsViewController.h"

@interface IOTCAddToGoogleCalendarsViewController ()

@property NSDictionary* dictCurrentCalendar;

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property NSMutableArray* arrGoogleCalendars;

@property GoogleOAuth* googleOAuth;

@property (weak, nonatomic) IBOutlet UIButton *add;
@property (weak, nonatomic) IBOutlet UIButton *logInButton;
@property (weak, nonatomic) IBOutlet UIButton *logOutButton;
@property (weak, nonatomic) IBOutlet UIButton *cancelButton;

@end

@implementation IOTCAddToGoogleCalendarsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = @"Add Task to a Google Calendar";
    
    //setting the class that manages the connection to google
    self.googleOAuth = [[GoogleOAuth alloc] initWithFrame:self.tableView.frame];
    self.googleOAuth.gOAuthDelegate = self;
    [self autorize];
    
    //setup the tableview which shows the google calendars
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    //setup autolayout constraints
    [self.add setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.logOutButton setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.logInButton setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.cancelButton setTranslatesAutoresizingMaskIntoConstraints:NO];
    
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.add attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:0.4 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.logInButton attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:0.8 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.logOutButton attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.20 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.cancelButton attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.60 constant:0]];

    
    // Do any additional setup after loading the view from its nib.
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)add:(id)sender {
    if(!self.dictCurrentCalendar)
    {
        UIAlertView* noCalendarAlert = [[UIAlertView alloc] initWithTitle:@"No calendar" message:@"Your google calendars cannot be loaded. Please try again." delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [noCalendarAlert show];
        return;
    }
    [self addEventToGoogleCalendar];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (IBAction)cancel:(id)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];

}

- (IBAction)logOut:(id)sender {
    [self revokeAccess:self];
    [self autorize];
}

- (IBAction)LogIn:(id)sender {
    [self autorize];
}


-(void) addEventToGoogleCalendar
{

    // Create the URL string of API needed to quick-add the event into the Google calendar.
    // Note that we specify the id of the selected calendar.
    NSString *apiURLString = [NSString stringWithFormat:@"https://www.googleapis.com/calendar/v3/calendars/%@/events/quickAdd",
                              [self.dictCurrentCalendar objectForKey:@"id"]];
    
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents = [[NSCalendar currentCalendar] components:NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit
                                                     fromDate:self.task.endDate];
    
    NSString*  strEventTextToPost = [NSString stringWithFormat:@"%@ %d/%d/%d at %d.%d", self.task.description, [dateComponents month], [dateComponents day], [dateComponents year], [dateComponents hour], [dateComponents minute]];
    
    [self.googleOAuth callAPI:apiURLString
               withHttpMethod:httpMethod_POST
           postParameterNames:[NSArray arrayWithObjects:@"calendarId", @"text", nil]
          postParameterValues:[NSArray arrayWithObjects:[self.dictCurrentCalendar objectForKey:@"id"], strEventTextToPost, nil]];
    
}

-(void) autorize
{
    [_googleOAuth authorizeUserWithClienID:@"242246237762-ovru864a32lt0rnegspvv19786u40uge.apps.googleusercontent.com"
                           andClientSecret:@"sWqqZvSXPrKo5UZVyJDFiihF"
                             andParentView:self.view
                                 andScopes:[NSArray arrayWithObject:@"https://www.googleapis.com/auth/calendar"]];
}


#pragma mark - GoogleOAuth delegate methods
-(void)authorizationWasSuccessful{
    // If user authorization is successful, then make an API call to get the calendar list.
    // For more infomation about this API call, visit:
    // https://developers.google.com/google-apps/calendar/v3/reference/calendarList/list
    [_googleOAuth callAPI:@"https://www.googleapis.com/calendar/v3/users/me/calendarList"
           withHttpMethod:httpMethod_GET
       postParameterNames:nil
      postParameterValues:nil];
}

-(void)responseFromServiceWasReceived:(NSString *)responseJSONAsString andResponseJSONAsData:(NSData *)responseJSONAsData{
    NSError *error;
    

    if ([responseJSONAsString rangeOfString:@"calendarList"].location != NSNotFound) {
        // If the response from Google contains the "calendarList" literal, then the calendar list
        // has been downloaded.
        
        // Get the JSON data as a dictionary.
        NSDictionary *calendarInfoDict = [NSJSONSerialization JSONObjectWithData:responseJSONAsData options:NSJSONReadingMutableContainers error:&error];
        
        if (error) {
            // This is the case that an error occured during converting JSON data to dictionary.
            // Simply log the error description.
            NSLog(@"%@", [error localizedDescription]);
        }
        else{
            // Get the calendars info as an array.
            NSArray *calendarsInfo = [calendarInfoDict objectForKey:@"items"];
            
            // If the arrGoogleCalendars array is nil then initialize it so to store each calendar as a NSDictionary object.
            self.arrGoogleCalendars = [NSMutableArray array];
            
            // Make a loop and get the next data of each calendar.
            for (int i=0; i<[calendarsInfo count]; i++) {
                // Store each calendar in a temporary dictionary.
                NSDictionary *currentCalDict = [calendarsInfo objectAtIndex:i];
                
                //only show calendars where the user is awolled to post
                if(![[currentCalDict objectForKey:@"accessRole"]  isEqual: @"owner"] && ![[currentCalDict objectForKey:@"accessRole"]  isEqual: @"writer"]) break;
                
                                // Create an array which contains only the desired data.
                NSArray *values = [NSArray arrayWithObjects:[currentCalDict objectForKey:@"id"],
                                   [currentCalDict objectForKey:@"summary"],
                                   nil];
                // Create an array with keys regarding the values on the previous array.
                NSArray *keys = [NSArray arrayWithObjects:@"id", @"summary", nil];
                
                // Add key-value pairs in a dictionary and then add this dictionary into the arrGoogleCalendars array.
                [self.arrGoogleCalendars addObject:
                 [[NSMutableDictionary alloc] initWithObjects:values forKeys:keys]];
            }
            
            // Set the first calendar as the selected one.
            self.dictCurrentCalendar = [[NSDictionary alloc] initWithDictionary:[self.arrGoogleCalendars objectAtIndex:0]];
            
                [self.tableView reloadData];
            [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
            self.add.enabled = YES;
            
        }
    }
}

- (IBAction)revokeAccess:(id)sender {
    // Revoke the access token.
    [_googleOAuth revokeAccessToken];
}

-(void)accessTokenWasRevoked{
    self.dictCurrentCalendar = nil;
    self.arrGoogleCalendars = nil;
    [self.tableView reloadData];
    self.add.enabled = NO;

}

-(void)errorOccuredWithShortDescription:(NSString *)errorShortDescription andErrorDetails:(NSString *)errorDetails{
    // Just log the error messages.
    NSLog(@"%@", errorShortDescription);
    NSLog(@"%@", errorDetails);
}

-(void)errorInResponseWithBody:(NSString *)errorMessage{
    // Just log the error message.
    NSLog(@"%@", errorMessage);
}


#pragma mark - tableviewDelegates
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.arrGoogleCalendars count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"SimpleTableItem";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }
    
    
    // Configure the cell...
    NSMutableDictionary* calendar = [self.arrGoogleCalendars objectAtIndex:indexPath.row];
    cell.textLabel.text = [calendar objectForKey:@"summary"];
    
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.dictCurrentCalendar = [self.arrGoogleCalendars objectAtIndex:indexPath.row];
}


@end
